import { defineStore } from 'pinia';
import { ref, computed } from 'vue';
import { ElMessage } from 'element-plus';
import axios from 'axios'; // 假设已安装axios
// 设置axios的基础URL
axios.defaults.baseURL = 'http://admin-lusiyi.ijelly.cn';
//登录API请求
const loginApi = async (username, password) => {
  try {
    const response = await axios.post('/api/auth/login', {
      username,
      password
    });
    return response.data.data; // 假设后端返回用户信息和token
  } catch (error) {
    throw new Error(error.response?.data?.message || 'login_failed');
  }
}
//注册API请求
const registerApi = async (username, password, email) => {
  try {
    const response = await axios.post('/api/auth/register', {
      username,
      password,
      email
    });
    return response.data; // 假设后端返回用户信息
  } catch (error) {
    throw new Error(error.response?.data?.message || 'registration_failed');
  }

}
//忘记密码-验证身份-重置密码
const resetPasswordApi = async (username, email, newPassword) => {
  try {
    const response = await axios.put('/api/users/reset-password-self', {
      username,
      email,
      newPassword
    });
    return response; // 假设后端返回成功信息
  } catch (error) {
    throw new Error(error.response?.data?.message || 'reset_password_failed');
  }
}
//刷新令牌ApI
const refreshTokenApi = async (refreshToken) => {
  try {
    const response = await axios.post('/api/auth/refresh', {
      refreshToken
    });
    return response.data.data; // 假设后端返回新的访问令牌和刷新令牌
  } catch (error) {
    throw new Error(error.response?.data?.message || 'refresh_token_failed');
  }
};
export const useAuthStore = defineStore('auth', () => {
  // 状态
  const userInfo = ref(null);
  const token = ref(localStorage.getItem('token') || sessionStorage.getItem('token'));
  const loginErrorCount = ref(parseInt(localStorage.getItem('loginErrorCount') || '0'));
  const refreshToken = ref(localStorage.getItem('refreshtoken') || sessionStorage.getItem('refreshtoken'));
  // 
  // 计算属性
  const isLoggedIn = computed(() => !!token.value);

  // 方法
  // 使用Map存储每个用户的错误次数和锁定时间
  const loginErrorMap = ref(new Map());
  //登录
  const login = async (username, password, rememberMe = false) => {
    try {
      // 检查该用户是否被锁定
      const userErrorInfo = loginErrorMap.value.get(username);
      if (userErrorInfo && userErrorInfo.lockedUntil > Date.now()) {
        const remainingTime = Math.ceil((userErrorInfo.lockedUntil - Date.now()) / 1000 / 60);
        ElMessage.error(`账号已被锁定，请 ${remainingTime} 分钟后再试`);
        throw new Error('account_locked');
      }

      // 调用登录API
      const { user, token: loginToken, refreshToken: refreshtoken } = await loginApi(username, password);

      // 登录成功，清除该用户的错误记录
      loginErrorMap.value.delete(username);

      // 存储用户信息和token
      userInfo.value = user;
      token.value = loginToken;
      refreshToken.value = refreshtoken;
      if (rememberMe) {
        localStorage.setItem('token', token.value);
        localStorage.setItem('refreshtoken', refreshToken.value);
        localStorage.setItem('userInfo', JSON.stringify(user));
      } else {
        sessionStorage.setItem('token', token.value);
        sessionStorage.setItem('refreshtoken', refreshToken.value);
        sessionStorage.setItem('userInfo', JSON.stringify(user));
      }

      return user;
    } catch (error) {
      if (error.message === 'account_locked') {
        // 后端返回锁定错误（如果后端实现了锁定逻辑）
        ElMessage.error('账号已被锁定，请联系管理员');
      } else {
        // 前端记录错误次数
        let userErrorInfo = loginErrorMap.value.get(username) || { count: 0, lockedUntil: 0 };
        userErrorInfo.count += 1;

        if (userErrorInfo.count >= 5) {
          userErrorInfo.lockedUntil = Date.now() + 30 * 60 * 1000; // 锁定30分钟
          localStorage.setItem(`loginError_${username}`, JSON.stringify(userErrorInfo));
          ElMessage.error('账号已被锁定，请30分钟后再试');
        } else {
          localStorage.setItem(`loginError_${username}`, JSON.stringify(userErrorInfo));
          ElMessage.error(`密码错误，还剩 ${5 - userErrorInfo.count} 次尝试机会`);
        }

        loginErrorMap.value.set(username, userErrorInfo);
      }
      throw error;
    }
  };
  //登出
  const logout = async (user) => {
    try {
      const response = await axios.post('/api/auth/logout', user, {
        headers: {
          'Authorization': `Bearer ${token.value}`
        }
      });
      // 清除状态
      userInfo.value = null;
      token.value = null;

      // 清除存储
      localStorage.removeItem('token');
      sessionStorage.removeItem('token');
      sessionStorage.removeItem('refreshtoken');
      localStorage.removeItem('userInfo');
      sessionStorage.removeItem('userInfo');
      return response; // 假设后端返回成功信息
    } catch (error) {
      throw error;
    }

  };

  // 初始化时从存储加载用户信息
  const initUserInfo = () => {
    if (token.value) {
      const storedUser = localStorage.getItem('userInfo') || sessionStorage.getItem('userInfo');
      if (storedUser) {
        userInfo.value = JSON.parse(storedUser);
      }
    }
  };
  //重置密码
  const resetPassword = async (username, email, newPassword) => {
    try {
      const response = await resetPasswordApi(username, email, newPassword);
      return response; // 假设后端返回成功信息
    } catch (error) {
      throw error;
    }
  }
  // 初始化
  initUserInfo();
  //注册
  const register = async (username, password, email) => {
    try {
      const user = await registerApi(username, password, email);
      return user;
    } catch (error) {
      throw error;
    }
  }
 // 刷新令牌方法
  const refreshTokens = async () => {
    try {
      const { token: newToken, refreshToken: newRefreshToken } = await refreshTokenApi(refreshToken.value);

      // 更新本地存储
      token.value = newToken;
      refreshToken.value = newRefreshToken;
      localStorage.setItem('token', token.value);
      localStorage.setItem('refreshtoken', refreshToken.value);

      // 更新 axios 默认的 Authorization 头
      axios.defaults.headers.common['Authorization'] = `Bearer ${token.value}`;
    } catch (error) {
      // 如果刷新令牌失败，提示用户重新登录
      ElMessage.error('登录已过期，请重新登录');
      localStorage.removeItem('token');
      localStorage.removeItem('refreshtoken');
      localStorage.removeItem('userInfo');
      sessionStorage.removeItem('token');
      sessionStorage.removeItem('refreshtoken');
      sessionStorage.removeItem('userInfo');
      throw error;
    }
  };

  // 设置 Axios 请求拦截器
  axios.interceptors.request.use(
    (config) => {
      if (token.value) {
        config.headers['Authorization'] = `Bearer ${token.value}`;
      }
      return config;
    },
    (error) => {
      return Promise.reject(error);
    }
  );

  // 设置 Axios 响应拦截器
  axios.interceptors.response.use(
    (response) => {
      return response;
    },
    async (error) => {
      if (error.response.status === 401 && !error.config._retry) {
        error.config._retry = true;

        try {
          await refreshTokens();
          return axios(error.config);
        } catch (refreshError) {
          throw refreshError;
        }
      }
      return Promise.reject(error);
    }
  );
  const setUserInfo = (newUserInfo) => {
    userInfo.value = newUserInfo
    // 同时更新本地存储
    if (localStorage.getItem('userInfo')) {
      localStorage.setItem('userInfo', JSON.stringify(newUserInfo))
    }
    if (sessionStorage.getItem('userInfo')) {
      sessionStorage.setItem('userInfo', JSON.stringify(newUserInfo))
    }
  }

  return {
    userInfo,
    token,
    isLoggedIn,
    login,
    logout,
    register,
    resetPassword,
    setUserInfo
  };
});